import 'package:flutter/material.dart';
import '../../../../core/controllers/base_controller.dart';
import '../../../../core/controllers/global_controller.dart';
import '../../../../core/storage/storage_service.dart';
import '../../../../core/network/dio_client.dart';

class HomeController extends BaseController {
  final StorageService _storageService = StorageService.instance;
  final DioClient _dioClient = DioClient.instance;
  
  @override
  void onInit() {
    super.onInit();
    setTitle('首页');
    loadHomeData();
  }

  // 加载首页数据
  Future<void> loadHomeData() async {
    await performAsyncOperation(() async {
      // 模拟加载数据
      await Future.delayed(const Duration(seconds: 1));
      showSuccessMessage('首页数据加载完成');
    });
  }

  // 测试网络请求
  Future<void> testNetworkRequest() async {
    showLoadingDialog(message: '正在测试网络请求...');
    
    try {
      // 模拟网络请求
      await Future.delayed(const Duration(seconds: 2));
      
      hideLoadingDialog();
      showSuccessMessage('网络请求测试成功');
    } catch (e) {
      hideLoadingDialog();
      showErrorMessage('网络请求测试失败: $e');
    }
  }

  // 测试本地存储
  Future<void> testLocalStorage() async {
    try {
      // 存储测试数据
      await _storageService.setUserPreference('test_key', 'test_value');
      
      // 读取测试数据
      final value = _storageService.getUserPreference<String>('test_key');
      
      if (value == 'test_value') {
        showSuccessMessage('本地存储测试成功');
      } else {
        showErrorMessage('本地存储测试失败');
      }
    } catch (e) {
      showErrorMessage('本地存储测试失败: $e');
    }
  }

  // 切换主题
  Future<void> toggleTheme() async {
    final globalController = GlobalController.instance;
    await globalController.toggleTheme();
    showSuccessMessage('主题切换成功');
  }

  // 切换语言
  Future<void> toggleLanguage() async {
    final globalController = GlobalController.instance;
    final currentLocale = globalController.locale;
    
    // 在中文和英文之间切换
    if (currentLocale.languageCode == 'zh') {
      await globalController.setLocale(const Locale('en', 'US'));
      showSuccessMessage('Language switched to English');
    } else {
      await globalController.setLocale(const Locale('zh', 'CN'));
      showSuccessMessage('语言切换为中文');
    }
  }

  // 刷新数据
  @override
  Future<void> onRefresh() async {
    await loadHomeData();
  }

  // 重试操作
  @override
  Future<void> onRetry() async {
    await loadHomeData();
  }
}